/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { Request, Response } from 'express';
import { isFunction } from 'lodash';
import Mock from 'mockjs';

/**
 *
 * @descriptions mock列表
 * @param p0
 * @param opts
 * @returns
 */
export function mockList(p0: any, opts?: any, req?: Request) {
  const { page = 1, size = 30, page_size = size } = req?.body;
  const { _random, _key = '', _id = 'id', _idMax = 6, _max = page_size, ...restOpts } = opts || {};
  const list: any[] = [];
  let len = 0;

  const isEmpty = _random && !!Math.round(Math.random());
  while (((len = list.length), len < _max) && !isEmpty) {
    list.push(
      Mock.mock(
        typeof p0 === 'function'
          ? p0(list)
          : {
              ...(_id
                ? {
                    [_id]: `${page}_` + `${list.length}`.padStart(_idMax, `0`),
                  }
                : {}),
              ...p0,
            },
      ),
    );
  }
  let k = _key;
  let extraData = null;
  if (Object.keys(restOpts).length > 0) {
    // 有其他配置项
    k = k || 'list';
    extraData = Mock.mock(restOpts);
  }
  if (k) {
    return { [k]: list, ...extraData };
  }
  return list;
}

/**
 *
 * @descriptions mock单项数据
 * @param data
 * @returns
 */
export function mockItem(data: any) {
  const { data: mockData } = Mock.mock(Array.isArray(data) ? { 'data|1': data } : { data });
  return mockData;
}

/**
 *
 * @descriptions 模拟数据响应
 * @param req
 * @param res
 */
export function mockResponse(params?: any, ag1: any = mockList, ag2: any = null) {
  return (req: Request, res: Response) => {
    if (typeof params === 'undefined') {
      res.send(
        Mock.mock({
          'data|1': [
            { code: 1, msg: 'error', data: {} },
            { code: 0, msg: 'success', data: !isFunction(ag1) ? ag1 : {} },
          ],
        }).data,
      );
      return;
    }

    let mockCreate = null;
    let opts = null;
    if (typeof ag1 === 'function') {
      mockCreate = ag1;
      opts = ag2;
    } else {
      // ag1 配置null时可以执行 mockItem;
      // ag2 配置了方法，ag1不为null，正确执行ag2;
      mockCreate = ag1 && typeof ag2 !== 'function' ? mockList : ag2 || mockItem;
      opts = ag1;
    }
    res.send({
      code: 0,
      msg: 'success',
      data: mockCreate(typeof params === 'function' ? params(req, res) : params, opts, req),
    });
  };
}
